<template>
  <div class="page-container">
    <div class="container">
    <el-input
        v-model="searchKeyword"
        placeholder="请输入关键词搜索"
        style="margin-bottom: 20px; width: 300px; border-radius: 20px;"
        @keyup.enter="handleSearch"
    >
      <template #suffix>
        <el-button  @click="handleSearch" style="border-radius: 20px;">查询</el-button>
      </template>
    </el-input>

    <el-tabs v-model="activeTab" type="card">
      <el-tab-pane label="全部用户信息" name="all">
        <el-table :data="employees" style="width: 100%" row-key="userId" :expand-row-keys="expandedRows">
          <el-table-column type="expand">
            <template #default="props">
              <div class="employee-details">
                <el-row :gutter="20">
                  <el-col :span="8">
                    <strong>用户名:</strong> {{ props.row.username }}
                  </el-col>
                  <el-col :span="8">
                    <strong>手机号:</strong> {{ props.row.phoneNumber }}
                  </el-col>
                  <el-col :span="8">
                    <strong>角色名:</strong> {{ props.row.roleName }}
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="8">
                    <strong>真名:</strong> {{ props.row.fullName }}
                  </el-col>
                  <el-col :span="8">
                    <strong>员工状态:</strong> {{ props.row.employmentStatus }}
                  </el-col>
                  <el-col :span="8">
                    <strong>部门名称:</strong> {{ props.row.departmentName }}
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="8">
                    <strong>职位名称:</strong> {{ props.row.positionName }}
                  </el-col>
                  <el-col :span="8">
                    <strong>基本工资:</strong> {{ props.row.baseSalary }}
                  </el-col>
                  <el-col :span="8">
                    <strong>绩效工资:</strong> {{ props.row.bonusSalary }}
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="8">
                    <strong>入职日期:</strong> {{ formatDate(props.row.hireDate) }}
                  </el-col>
                  <el-col :span="8">
                    <strong>离职日期:</strong> {{ formatDate(props.row.resignationDate)}}
                  </el-col>
                  <el-col :span="8">
                    <strong>创建时间:</strong> {{ props.row.createdTime }}
                  </el-col>
                </el-row>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="用户名"></el-table-column>
          <el-table-column prop="phoneNumber" label="手机号"></el-table-column>
          <el-table-column prop="roleName" label="角色名"></el-table-column>
          <el-table-column prop="fullName" label="真名"></el-table-column>
          <el-table-column prop="employmentStatus" label="员工状态"></el-table-column>
          <el-table-column fixed="right" label="操作" width="120">
            <template #default="scope">
              <el-button size="small" @click.stop="editEmployee(scope.row)">编辑</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
            background
            layout="prev, pager, next"
            :total="pagination.total"
            :page-size="pagination.size"
            v-model:current-page="pagination.page"
            @current-change="fetchEmployees"
            style="margin-top: 20px; text-align: center;"
        />
      </el-tab-pane>
      <el-tab-pane label="在职员工" name="active">
        <el-table :data="activeEmployees" style="width: 100%" row-key="userId" :expand-row-keys="expandedRows">
          <el-table-column type="expand">
            <template #default="props">
              <div class="employee-details">
                <el-row :gutter="20">
                  <el-col :span="8">
                    <strong>用户名:</strong> {{ props.row.username }}
                  </el-col>
                  <el-col :span="8">
                    <strong>手机号:</strong> {{ props.row.phoneNumber }}
                  </el-col>
                  <el-col :span="8">
                    <strong>角色名:</strong> {{ props.row.roleName }}
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="8">
                    <strong>真名:</strong> {{ props.row.fullName }}
                  </el-col>
                  <el-col :span="8">
                    <strong>员工状态:</strong> {{ props.row.employmentStatus }}
                  </el-col>
                  <el-col :span="8">
                    <strong>部门名称:</strong> {{ props.row.departmentName }}
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="8">
                    <strong>职位名称:</strong> {{ props.row.positionName }}
                  </el-col>
                  <el-col :span="8">
                    <strong>基本工资:</strong> {{ props.row.baseSalary }}
                  </el-col>
                  <el-col :span="8">
                    <strong>绩效工资:</strong> {{ props.row.bonusSalary }}
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="8">
                    <strong>入职日期:</strong> {{ formatDate(props.row.hireDate)}}
                  </el-col>
                  <el-col :span="8">
                    <strong>离职日期:</strong> {{ formatDate(props.row.resignationDate) }}
                  </el-col>
                  <el-col :span="8">
                    <strong>创建时间:</strong> {{ props.row.createdTime }}
                  </el-col>
                </el-row>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="用户名"></el-table-column>
          <el-table-column prop="phoneNumber" label="手机号"></el-table-column>
          <el-table-column prop="roleName" label="角色名"></el-table-column>
          <el-table-column prop="fullName" label="真名"></el-table-column>
          <el-table-column prop="employmentStatus" label="员工状态"></el-table-column>
          <el-table-column fixed="right" label="操作" width="120">
            <template #default="scope">
              <el-button size="small" @click.stop="editEmployee(scope.row)">编辑</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
            background
            layout="prev, pager, next"
            :total="pagination.total"
            :page-size="pagination.size"
            v-model:current-page="pagination.page"
            @current-change="fetchEmployees"
            style="margin-top: 20px; text-align: center;"
        />
      </el-tab-pane>
      <el-tab-pane label="未认证用户" name="unauthenticated">
        <el-table :data="unauthenticatedEmployees" style="width: 100%" row-key="userId" :expand-row-keys="expandedRows">
          <el-table-column type="expand">
            <template #default="props">
              <div class="employee-details">
                <el-row :gutter="20">
                  <el-col :span="8">
                    <strong>用户名:</strong> {{ props.row.username }}
                  </el-col>
                  <el-col :span="8">
                    <strong>手机号:</strong> {{ props.row.phoneNumber }}
                  </el-col>
                  <el-col :span="8">
                    <strong>角色名:</strong> {{ props.row.roleName }}
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="8">
                    <strong>真名:</strong> {{ props.row.fullName }}
                  </el-col>
                  <el-col :span="8">
                    <strong>员工状态:</strong> {{ props.row.employmentStatus }}
                  </el-col>
                  <el-col :span="8">
                    <strong>部门名称:</strong> {{ props.row.departmentName }}
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="8">
                    <strong>职位名称:</strong> {{ props.row.positionName }}
                  </el-col>
                  <el-col :span="8">
                    <strong>基本工资:</strong> {{ props.row.baseSalary }}
                  </el-col>
                  <el-col :span="8">
                    <strong>绩效工资:</strong> {{ props.row.bonusSalary }}
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="8">
                    <strong>入职日期:</strong> {{ formatDate(props.row.hireDate) }}
                  </el-col>
                  <el-col :span="8">
                    <strong>离职日期:</strong> {{ formatDate(props.row.resignationDate) }}
                  </el-col>
                  <el-col :span="8">
                    <strong>创建时间:</strong> {{ props.row.createdTime }}
                  </el-col>
                </el-row>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="用户名"></el-table-column>
          <el-table-column prop="phoneNumber" label="手机号"></el-table-column>
          <el-table-column prop="roleName" label="角色名"width="120"></el-table-column>
          <el-table-column fixed="right" label="操作" >
            <template #default="scope">
              <el-button size="small" @click.stop="editEmployee(scope.row)">编辑</el-button>
              <!-- 删除按钮 -->
              <el-button size="small" type="danger" @click.stop="deleteEmployee(scope.row.userId)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
            background
            layout="prev, pager, next"
            :total="pagination.total"
            :page-size="pagination.size"
            v-model:current-page="pagination.page"
            @current-change="fetchEmployees"
            style="margin-top: 20px; text-align: center;"
        />
      </el-tab-pane>
      <el-tab-pane label="离职员工" name="inactive">
        <el-table :data="inactiveEmployees" style="width: 100%" row-key="userId" :expand-row-keys="expandedRows">
          <el-table-column type="expand">
            <template #default="props">
              <div class="employee-details">
                <el-row :gutter="20">
                  <el-col :span="8">
                    <strong>用户名:</strong> {{ props.row.username }}
                  </el-col>
                  <el-col :span="8">
                    <strong>手机号:</strong> {{ props.row.phoneNumber }}
                  </el-col>
                  <el-col :span="8">
                    <strong>角色名:</strong> {{ props.row.roleName }}
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="8">
                    <strong>真名:</strong> {{ props.row.fullName }}
                  </el-col>
                  <el-col :span="8">
                    <strong>员工状态:</strong> {{ props.row.employmentStatus }}
                  </el-col>
                  <el-col :span="8">
                    <strong>部门名称:</strong> {{ props.row.departmentName }}
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="8">
                    <strong>职位名称:</strong> {{ props.row.positionName }}
                  </el-col>
                  <el-col :span="8">
                    <strong>基本工资:</strong> {{ props.row.baseSalary }}
                  </el-col>
                  <el-col :span="8">
                    <strong>绩效工资:</strong> {{ props.row.bonusSalary }}
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="8">
                    <strong>入职日期:</strong> {{ formatDate(props.row.hireDate) }}
                  </el-col>
                  <el-col :span="8">
                    <strong>离职日期:</strong> {{ formatDate(props.row.resignationDate) }}
                  </el-col>
                  <el-col :span="8">
                    <strong>创建时间:</strong> {{ props.row.createdTime }}
                  </el-col>
                </el-row>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="用户名"></el-table-column>
          <el-table-column prop="phoneNumber" label="手机号"></el-table-column>
          <el-table-column prop="roleName" label="角色名"></el-table-column>
          <el-table-column prop="fullName" label="真名"></el-table-column>
          <el-table-column prop="employmentStatus" label="员工状态"></el-table-column>
          <el-table-column fixed="right" label="操作" width="120">
            <template #default="scope">
              <el-button size="small" @click.stop="editEmployee(scope.row)">编辑</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
            background
            layout="prev, pager, next"
            :total="pagination.total"
            :page-size="pagination.size"
            v-model:current-page="pagination.page"
            @current-change="fetchEmployees"
            style="margin-top: 20px; text-align: center;"
        />
      </el-tab-pane>
    </el-tabs>

    <el-dialog v-model="dialogVisible" title="员工详情">
      <pre>{{ selectedEmployee }}</pre>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog v-model="editDialogVisible" title="编辑员工信息">
      <el-form :model="editingEmployee" :rules="rules" ref="editFormRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editingEmployee.username"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phoneNumber">
          <el-input v-model="editingEmployee.phoneNumber"></el-input>
        </el-form-item>
        <el-form-item label="角色权限" prop="roleName">
          <el-select v-model="editingEmployee.roleName" placeholder="请选择员工权限">
            <el-option label="管理员" value="管理员"></el-option>
            <el-option label="普通员工" value="普通员工"></el-option>
            <el-option label="人事经理" value="人事经理"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="真名" prop="fullName">
          <el-input v-model="editingEmployee.fullName"></el-input>
        </el-form-item>
        <el-form-item label="员工状态" prop="employmentStatus">
          <el-select v-model="editingEmployee.employmentStatus" placeholder="请选择员工状态">
            <el-option label="在职" value="在职"></el-option>
            <el-option label="离职" value="离职"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部门名称" prop="departmentName">
          <el-input v-model="editingEmployee.departmentName" readonly></el-input>
        </el-form-item>
        <el-form-item label="职位名称" prop="positionName">
          <el-select v-model="editingEmployee.positionName" placeholder="请选择职位" @change="selectPosition">
            <el-option v-for="position in positions" :key="position.id" :label="position.name" :value="position.name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="基本工资" prop="baseSalary">
          <el-input v-model="editingEmployee.baseSalary"></el-input>
        </el-form-item>
        <el-form-item label="绩效工资" prop="bonusSalary">
          <el-input v-model="editingEmployee.bonusSalary"></el-input>
        </el-form-item>
        <el-form-item label="入职日期" prop="hireDate">
          <el-date-picker
              v-model="editingEmployee.hireDate"
              type="datetime"
              placeholder="选择入职日期"
          />
        </el-form-item>
        <el-form-item label="离职日期" prop="resignationDate">
          <el-date-picker
              v-model="editingEmployee.resignationDate"
              type="datetime"
              placeholder="如未离职请勿填写"
          />
        </el-form-item>
        <el-form-item label="创建时间" prop="createdTime">
          <el-input v-model="editingEmployee.createdTime" readonly></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
    <span class="dialog-footer">
      <el-button @click="cancel()">取消</el-button>
      <el-button type="primary" @click="submitForm">保存</el-button>
    </span>
      </template>
    </el-dialog>
  </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import {ElMessage, ElMessageBox} from "element-plus";
const activeTab = ref('all');
const employees = ref([]);
const unauthenticatedEmployees = ref([]);
const activeEmployees = ref([]);
const inactiveEmployees = ref([]);
const dialogVisible = ref(false);
const editDialogVisible = ref(false);
const selectedEmployee = ref({});
const editingEmployee = ref({
  username: '',
  phoneNumber: '',
  roleName: '',
  fullName: '',
  employmentStatus: '',
  departmentName: '',
  positionName: '',
  baseSalary: '',
  bonusSalary: '',
  hireDate: '',
  resignationDate: '',
  createdTime: '',
  positionId: null,
  departmentId: null});
const searchKeyword = ref('');
const positions = ref([]);
const pagination = ref({
  page: 1,
  size: 10,
  total: 0,
});
const expandedRows = ref([]);
const rules={
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  phoneNumber: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
  roleName: [{ required: true, message: '请选择角色权限', trigger: 'change' }],
  fullName: [{ required: true, message: '请输入真名', trigger: 'blur' }],
  employmentStatus: [{ required: true, message: '请选择员工状态', trigger: 'change' }],
  departmentName: [{ required: true, message: '请输入部门名称', trigger: 'blur' }],
  positionName: [{ required: true, message: '请输入职位名称', trigger: 'change' }],
  baseSalary: [{ required: true, message: '请输入基本工资', trigger: 'blur' }],
  bonusSalary: [{ required: true, message: '请输入绩效工资', trigger: 'blur' }],
  hireDate: [{ required: true, message: '请输入入职日期', trigger: 'blur' }],
  resignationDate: [{message: '请输入离职日期', trigger: 'blur' }],
  createdTime: [{ required: true, message: '请输入创建时间', trigger: 'blur' }]
}
const fetchEmployees = async () => {
  try {
    const response = await axios.get('http://localhost:8080/admin/employees', {
      params: {
        page: pagination.value.page,
        size: pagination.value.size,
        keyword: searchKeyword.value,
      },
    });
    employees.value = response.data.data.records;
    pagination.value.total = response.data.data.total;
    categorizeEmployees();
  } catch (error) {
    console.error('获取员工信息失败:', error);
  }
};

const categorizeEmployees = () => {
  unauthenticatedEmployees.value = employees.value.filter(emp => emp.roleName === '未认证');
  activeEmployees.value = employees.value.filter(emp => emp.employmentStatus === '在职');
  inactiveEmployees.value = employees.value.filter(emp => emp.employmentStatus === '离职');
};
const editFormRef = ref(null);
const submitForm = () => {
  editFormRef.value.validate((valid) => {
    if (valid) {
      saveEdit();
    } else {
      console.log('表单验证失败！');
      return false;
    }
  });}
const deleteEmployee = async (userId) => {
  try {
    // 弹出确认框
    const confirmDelete = await ElMessageBox.confirm(
        '确定要删除该用户吗？',
        '警告',
        {
          confirmButtonText: '删除',
          cancelButtonText: '取消',
          type: 'warning',
        }
    );
    // 如果用户确认删除
    if (confirmDelete === 'confirm') {
      // 向后端发送删除请求
      const response= await axios.delete(`http://localhost:8080/admin/employees/${userId}`);
      // 从列表中移除该员工
      if(response.data){
        unauthenticatedEmployees.value = unauthenticatedEmployees.value.filter(emp => emp.userId !== userId);
      }else {
        ElMessage.error("删除失败，请检查目标权限")}
    }
  } catch (error) {
    console.error('删除员工失败:', error);
  }
};

const handleSearch = () => {
  pagination.value.page = 1;
  fetchEmployees();
};
const fetchPositions = async () => {
  try {
    const response = await axios.get('http://localhost:8080/positions');
    positions.value = response.data;
  } catch (error) {
    console.error('Error fetching positions:', error);
  }
};
const selectPosition = (positionName) => {
  console.log(positionName);
  const selectedPosition = positions.value.find(position => position.name === positionName);
  console.log(selectedPosition.departmentName);
  if (selectedPosition) {
    editingEmployee.value.positionId = selectedPosition.id;
    editingEmployee.value.departmentName = selectedPosition.departmentName;
    editingEmployee.value.departmentId = selectedPosition.departmentId;
  }
};
const editEmployee = (row) => {
  editingEmployee.value = { ...row };
  editDialogVisible.value = true;
};

const saveEdit = async () => {
  try {
    await axios.post(`http://localhost:8080/admin/employees/`,editingEmployee.value);
    editDialogVisible.value = false;
    await fetchEmployees(); // Refresh the list after saving
  } catch (error) {
    console.error('更新员工信息失败:', error);
  }
};
function cancel(){
  editDialogVisible.value = false;
  console.log(editingEmployee.value);
}
// 日期格式化
const formatDate = (date) => {
  if(!date) return '';
  const d = new Date(date);
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, '0'); // 月份补零
  const day = String(d.getDate()).padStart(2, '0'); // 日期补零

  return `${year}-${month}-${day}`;
};
onMounted(() => {
  fetchPositions();
  fetchEmployees();
  // 可以在这里做一些初始化操作
});
</script>

<style scoped>
.employee-management {
  padding: 20px;
}
.container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}
.employee-details {
  font-size: 14px;
  margin-left: 20px;
}

.employee-details .el-row {
  margin-bottom: 20px;
}
.employee-details .el-col {
  border-radius: 4px;
}

.el-table th {
  background-color: #f4f4f4;
}
</style>
